<html>
<head>

<title>Groovy Goodness: Multiple Assignments</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Multiple Assignments</h3>

<div class="post">
<p>Since Groovy 1.6 we can define and assign values to several variables at once. This is especially useful when a method returns multiple values and we want to assign them to separate variables.</p>
<pre class="brush:groovy">
// Assign and declare variables.
def (username, email) = ['mrhaki', 'email@host.com']
assert 'mrhaki' == username
assert 'email@host.com' == email

// We can assign later than the definition of the variables.
int housenr
String streetname
(streetname, housenr) = ['Old Street', 42]
assert 42 == housenr
assert 'Old Street' == streetname

// We can also use type declerations.
def (String streetName, int houseNumber) = ['Old Street', 42]
assert 42 == houseNumber
assert 'Old Street' == streetName

// Return value of method can be assigned to multiple variables.
def iAmHere() {
    [29.20090, 12.90391]
}
def (coordX, coordY) = iAmHere()
assert coordX == 29.20090
assert coordY == 12.90391

// More values than variables: extra values are ignored.
def (a, b, c) = ['a', 'b', 'c', 'd']
assert 'a' == a
assert 'b' == b
assert 'c' == c

// Less values than variables: variable is not set.
def (x, y, z) = [100, 200]
assert 100 == x
assert 200 == y
assert !z

// Useful for getting regular expressions matching groups.
def money  = '12 Euro' 
def regexp = /(\d+) (\w+)/
def (exp, amount, currency) = (money =~ regexp)[0]
assert '12' == amount
assert 'Euro' == currency

</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>